package com.lbb.MVCFrameWork.servlets;

import com.lbb.MVCFrameWork.annotations.*;
import com.lbb.MVCFrameWork.pojo.Handler;
import com.lbb.demo.Service.DemoService;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LbbDispatcherServlet extends HttpServlet {

    //保存配置文件配置数据
    private Properties properties = new Properties();

    //ioc容器
    private Map<String,Object> ioc = new HashMap<>();

    //存放url和method的映射
    //private Map<String, Method> handlerMapping = new HashMap<>();
    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        //2.扫描注解
        doScan(properties.getProperty("scanPackage"));
        //3.初始化bean对象,基于classNames缓存的类的全限定类名，以及反射技术，完成对象创建和管理
        doInstance();
        //4.实现依赖注入
        doAutoWired();
        //5.构造一个HandlerMapping处理器映射器，将url和Method建立映射关系
        initHandlerMapping();
        System.out.println("springmvc初始化完成");
        //等待请求的进入
    }
    /*
    * 构造⼀个HandlerMapping处理器映射器最关键的环节
      ⽬的：将url和method建⽴关联
    * */
    private void initHandlerMapping() {
        if(ioc.isEmpty()) return;
        //容器中有对象，可以进行以来处理
        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            //获取ioc中当前遍历的对象的class类型
            Class<?> aClass = entry.getValue().getClass();
            //不是controllerlei无需处理url
            if(!aClass.isAnnotationPresent(LbbController.class)){
                continue;
            }

            String baseUrl = "";
            if(aClass.isAnnotationPresent(LbbRequestMapping.class)){
                LbbRequestMapping annotation = aClass.getAnnotation(LbbRequestMapping.class);
                baseUrl = annotation.value();  //等同于/demo
            }

            //获取方法
            Method[] methods = aClass.getMethods();
            for(int i = 0;i < methods.length;i++){
                Method method=  methods[i];
                //⽅法没有标识LagouRequestMapping，就不处理
                if(!method.isAnnotationPresent(LbbRequestMapping.class)){continue;}

                // 如果标识，就处理
                LbbRequestMapping annotation = method.getAnnotation(LbbRequestMapping.class);
                String methodUrl = annotation.value();// /query
                String url = baseUrl + methodUrl;//拼接出url
                //把method所有信息及url封装为⼀个Handler
                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));

                //处理security注解
                //类上有security，该标注用户名可以访问该类所有handle
                if(aClass.isAnnotationPresent(LbbSecurity.class) || method.isAnnotationPresent(LbbSecurity.class)){
                    if(aClass.isAnnotationPresent(LbbSecurity.class)){
                        handler.getSecurityMapping().addAll(Arrays.asList(aClass.getAnnotation(LbbSecurity.class).value()));
                    }

                    if(method.isAnnotationPresent(LbbSecurity.class)){
                        handler.getSecurityMapping().addAll(Arrays.asList(method.getAnnotation(LbbSecurity.class).value()));
                    }
                }

                //计算⽅法的参数位置信息 query(HttpServletRequestrequest, HttpServletRequestrequest response,String name)
                //此处没有考虑其他基本类型，不然太过繁琐，只考虑HttpServletRequestrequest，HttpServletRequestrequest，String
                Parameter[] parameters = method.getParameters();
                for(int j = 0;j < parameters.length;j++){
                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        //如果是request和response对象，那么参数名称写
                        //HttpServletRequest和HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(),j);
                    }
                }

                //建⽴url和method之间的映射关系（map缓存起来）
                handlerMapping.add(handler);
            }
        }
    }

    //实现依赖注入
    private void doAutoWired() {
        if(ioc.isEmpty()) return;
        //容器中有对象，可以进行以来处理
        //遍历ioc中所有对象，查看对象中的字段，是否有@LbbAutowired注解，如果有需要维护依赖注⼊关系
        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            //获取获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            if(declaredFields.length == 0) {continue;}
            // 遍历字段判断处理
            for(int i = 0;i < declaredFields.length;i++){
                Field declaredFieldfield = declaredFields[i];// @LbbAutowired   private DemoService demoService;
                if(!declaredFieldfield.isAnnotationPresent(LbbAutowired.class)){//没有该注解
                    continue;
                }

                //有该注解
                LbbAutowired annotation = declaredFieldfield.getAnnotation(LbbAutowired.class);
                String beanName = annotation.value();// 需要注⼊的bean的id
                if("".equals(beanName.trim())){// 没有配置具体的bean id，那就需要根据当前字段类型注⼊（接⼝注⼊） IDemoService
                    beanName = declaredFieldfield.getType().getName();

                    //开启赋值
                    declaredFieldfield.setAccessible(true);

                    try {
                        declaredFieldfield.set(entry.getValue(),ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //IOC容器，基于classNames缓存的类的全限定类名，以及反射技术，完成对象创建和管理
    private void doInstance() {
        //判断classNames是否为空
        if(classNames.size() == 0) return;
        try{
            //遍历classNames，利用反射构建对象
            for(int i = 0; i < classNames.size();i++){
                String className = classNames.get(i);  //值为com.lbb.demo.Controller.DemoController
                //反射
                Class<?> aClass = Class.forName(className);
                //判断是controller还是service
                if(aClass.isAnnotationPresent(LbbController.class)){
                    //controller的id此处不做过多处理，不取value了，就拿类的⾸字⺟⼩写作为id，保存到ioc中
                    String simpleName = aClass.getSimpleName();
                    //首字母小写
                    String lowFirstsimpleName = lowerFirst(simpleName);
                    //创建实例对象
                    Object o = aClass.getDeclaredConstructor().newInstance();
                    //放入ioc容器中
                    ioc.put(lowFirstsimpleName,o);
                }else if(aClass.isAnnotationPresent(LbbService.class)){
                    //获取注解
                    LbbService annotation = aClass.getAnnotation(LbbService.class);
                    //获取注解中的value值
                    String beanName = annotation.value();

                    //如果指定了id值，即value不为空，就以value为bean的id
                    if(!"".equals(beanName.trim())){
                        ioc.put(beanName,aClass.getDeclaredConstructor().newInstance());
                    }else{
                        //如果没有指定，就以类名⾸字⺟⼩写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName,aClass.getDeclaredConstructor().newInstance());
                    }
                    //service层往往是有接⼝的，⾯向接⼝开发，此时再以接⼝名为id，
                    //放⼊⼀份对象到ioc中，便于后期根据接⼝类型注⼊(Autowired)
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for(int j = 0;j < interfaces.length;j++){
                        Class<?> anInterface = interfaces[j];
                        //以接⼝的全限定类名作为id放⼊
                        ioc.put(anInterface.getName(),aClass.getDeclaredConstructor().newInstance());
                    }
                }else{
                    continue;
                }

            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    //首字母小写
    private String lowerFirst(String s){
        char[] chars = s.toCharArray();
        if(chars[0] >= 'A' && chars[0] <= 'Z'){
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    //保存类的全限定名，后续实例化使用
    private List<String> classNames = new ArrayList<>();
    //扫描注解,获得类名
    //scanPackage：com.lbb.demo，需要从package获得磁盘上的文件夹（File） 要将com.lbb.demo转化为com/lbb/demo
    private void doScan(String scanPackage) {
        //1.获取包的磁盘url地址,并构建File
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);

        //2.递归遍历File，获得类名
        File[] files = pack.listFiles();
        for(File file:files){
            if(file.isDirectory()){//子package
                doScan(scanPackage + "." + file.getName());
            }else{//获取类名并保存
                String className = scanPackage + "." + file.getName().replaceAll(".class","");
                classNames.add(className);
            }
        }

    }

    //加载配置文件 springmvc.properties
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    //处理请求
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 根据uri获取到能够处理当前请求的hanlder（从handlermapping中（list））
        Handler handler = getHandler(req);
        if(handler == null){
            resp.getWriter().println("404 not found");
            return;
        }

        //校验security用户名
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        if(username.isEmpty()){
            resp.getWriter().println("请输入用户名");
        }
        if(!handler.getSecurityMapping().contains(username)){
            resp.getWriter().println("用户" + username +"没有访问权限");
            return;
        }



        //参数绑定
        //获取所有参数类型数组，这个数组的⻓度就是我们最后要传⼊的args数组的⻓度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        // 根据上述数组⻓度创建⼀个新的数组（参数数组，是要传⼊反射调⽤的）
        Object[] paraValues = new Object[parameterTypes.length];

        //以下就是为了向参数数组中塞值，⽽且还得保证参数的顺序和⽅法中形参顺序⼀致
        Map<String, String[]> parameterMap = req.getParameterMap();

        //遍历request中所有参数 （填充除了request，response之外的参数）
        for(Map.Entry<String,String[]> entry:parameterMap.entrySet()){
            // name=1&name=2 name [1,2]
            String value = StringUtils.join(entry.getValue(),",");//1,2
            //如果参数和⽅法中的参数匹配上了，填充数据
            if(!handler.getParamIndexMapping().containsKey(entry.getKey())){
                continue;
            }

            //⽅法形参确实有该参数，找到它的索引位置，对应的把参数值放⼊paraValues
            Integer index = handler.getParamIndexMapping().get(entry.getKey());
            //把前台传递过来的参数值填充到对应的位置去
            paraValues[index] = value;
        }

        //填充req，res
        int reqIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[reqIndex] = req;

        int resIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[resIndex] = resp;

        //最终调⽤handler的method属性
        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()) return null;
        String url = req.getRequestURI();
        for(Handler handler:handlerMapping){
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }

}
